﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.销售.Sales;

namespace ERP_SaaS_WinForm.销售
{
    /// <summary>
    /// 客户选择窗体
    /// 用于在销售模块中选择客户，提供客户列表显示和搜索功能
    /// </summary>
    public partial class Client : Form
    {
        #region 字段定义
        
        /// <summary>
        /// 客户列表 - 存储从API获取的客户数据
        /// </summary>
        private List<SaleClinentDTO> clientList = new List<SaleClinentDTO>();

        #endregion

        #region 属性定义
        
        /// <summary>
        /// 选中的客户 - 用户选择的客户对象
        /// </summary>
        public SaleClinentDTO SelectedClient { get; private set; }

        #endregion

        /// <summary>
        /// 构造函数 - 初始化客户选择窗体
        /// </summary>
        public Client()
        {
            InitializeComponent();
            
            // 设置窗体显示位置为父窗体中心
            this.StartPosition = FormStartPosition.CenterParent;
            
            // 设置窗体标题
            this.Text = "选择客户";
            
            // 绑定窗体加载事件
            this.Load += Client_Load;
        }

        /// <summary>
        /// 窗体加载事件 - 初始化客户数据
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void Client_Load(object sender, EventArgs e)
        {
            // 加载客户数据，初始不进行筛选
            await LoadClientDataAsync(null);
        }

        /// <summary>
        /// 异步加载客户数据
        /// 从API获取客户列表并绑定到DataGridView
        /// </summary>
        /// <param name="clientName">客户名称筛选条件，可为null</param>
        /// <returns>异步任务</returns>
        private async Task LoadClientDataAsync(string clientName)
        {
            try
            {
                // API基础地址
                string baseUrl = "http://10.223.8.6:3530/api/Client/GetClient";
                
                // 构建查询参数列表
                var queryParams = new List<string>();
                if (!string.IsNullOrWhiteSpace(clientName)) 
                {
                    queryParams.Add($"clientName={clientName.Trim()}");
                }
                
                // 拼接完整的URL
                string url = queryParams.Count > 0 ? $"{baseUrl}?{string.Join("&", queryParams)}" : baseUrl;

                // 发送HTTP请求获取客户数据
                using (HttpClient http = new HttpClient())
                {
                    HttpResponseMessage response = await http.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string json = await response.Content.ReadAsStringAsync();
                    
                    // 反序列化API响应
                    SaleApiResponse api = JsonConvert.DeserializeObject<SaleApiResponse>(json);
                    
                    if (api.code == 200)
                    {
                        // 成功获取数据，更新客户列表并绑定到DataGridView
                        clientList = api.data ?? new List<SaleClinentDTO>();
                        dgvClients.DataSource = clientList;
                    }
                    else
                    {
                        // API返回错误，显示错误信息
                        MessageBox.Show($"查询失败: {api.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并显示错误信息
                MessageBox.Show($"获取客户数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// 根据输入的客户名称搜索客户
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            // 根据搜索框中的客户名称加载数据
            await LoadClientDataAsync(txtSearchName.Text);
        }

        /// <summary>
        /// 确定按钮点击事件
        /// 确认选择当前选中的客户并关闭窗体
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            // 检查是否有选中的行
            if (dgvClients.CurrentRow == null)
            {
                MessageBox.Show("请先选择一条客户记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 获取选中的客户对象
            SelectedClient = dgvClients.CurrentRow.DataBoundItem as SaleClinentDTO;
            if (SelectedClient == null)
            {
                MessageBox.Show("无法获取所选客户信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            // 设置对话框结果为OK并关闭窗体
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// 取消按钮点击事件
        /// 取消选择并关闭窗体
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            // 设置对话框结果为Cancel并关闭窗体
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// DataGridView单元格双击事件
        /// 双击客户行时自动确认选择
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void dgvClients_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否点击了有效的行
            if (e.RowIndex >= 0)
            {
                // 模拟点击确定按钮
                btnOk_Click(sender, EventArgs.Empty);
            }
        }
    }
}
